package com.example.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.mapper.LogLoadMapper;
import com.example.pojo.Operate;
import com.example.utils.JwtUtils;
import com.google.gson.JsonObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private LogLoadMapper logLoadMapper;

    @Around("@annotation(com.example.anno.Log)")
    /*@Around("execution(* com.example.service.impl.*Impl.*(..))")*/
    public Object LogLoad(ProceedingJoinPoint joinPoint) throws Throwable {
        String jwt = httpServletRequest.getHeader("token");
        Claims claims = jwtUtils.parseJwtToken(jwt);
        Integer id = (Integer) claims.get("id");
        LocalDateTime now = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        String returnValue = JSONObject.toJSONString(result);
        long end = System.currentTimeMillis();
        long costTime = end - start;
        Operate operate = new Operate(id, now, className, methodName, methodParams, returnValue, costTime);
        logLoadMapper.insert(operate);
        log.info("记录操作日志:{}",operate);
        return result;
    }
    @Around("@annotation(com.example.anno.TimeLog)")
    public Object TimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String method = joinPoint.getSignature().getName();
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        log.info("{}方法执行耗时:{}ms",method,(end-start));
        return proceed;
    }
}
